//
//  DingWeiViewController.m
//  NewProject
//
//  Created by 王嘉琪 on 2017/6/7.
//  Copyright © 2017年 李航飞. All rights reserved.
//

#import "DingWeiViewController.h"
#import "DingWeiTableViewCell.h"

#import "AddressViewController.h"

#import <CoreLocation/CoreLocation.h>

@interface DingWeiViewController ()<UITableViewDataSource, UITableViewDelegate,CLLocationManagerDelegate>
@property (nonatomic,strong) NSMutableArray *arr;
@property (assign,nonatomic)double latitude;//经纬度
@property (assign,nonatomic)double longitude;//纬度
@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation DingWeiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getJIngWei];
    [self firstGetMessage];
    
    self.title=@"定位";
    [self.view setBackgroundColor:[UIColor whiteColor]];
   
    // Do any additional setup after loading the view.
}
- (void)firstGetMessage{
    AFHTTPSessionManager*manager=[AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = nil;
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/plain", nil];
    
    NSString*urlstr=[NSString stringWithFormat:@"http://www.lnwuyou.com/sc/index.php?g=portal&m=index&a=locate&lat=39.983424&lng=116.322987"];
//    ,[NSString stringWithFormat:@"%f", _latitude],[NSString stringWithFormat:@"%f", _longitude]
    [manager GET:urlstr parameters:nil  progress:nil success:^(NSURLSessionDataTask *operation, id responseObject) {
        NSLog(@"111%@",responseObject);
        NSDictionary*dic=[[NSDictionary alloc]init];
        dic=responseObject;
        if([dic[@"status"] isEqualToString:@"1"]){
            _arr=dic[@"data"][@"result"][@"pois"];
            [self setUpView];
            NSLog(@"%@",dic);
        }else{
            UIAlertView*alert = [[UIAlertView alloc] initWithTitle:@""
                                                           message:dic[@"msg"] delegate:self
                                                 cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            [alert show];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        NSLog(@"请求出错了: - %@ \n%@",
              [error localizedDescription],
              [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    }];

}
- (void)setUpView{
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64+54*kScrenHidth, self.view.frame.size.width, self.view.frame.size.height-54*kScrenHidth-80*kScrenHidth-64) style:UITableViewStylePlain];
    //   _arr=[[NSMutableArray alloc] initWithObjects:@"和泰大厦",@"和泰大厦",@"和泰大厦",@"和泰大厦", @"和泰大厦",nil];
    //    arr=[@"和泰大厦",@"和泰大厦",@"和泰大厦",@"和泰大厦",nil];
    
    //    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //去掉tableView自带分割线
    tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
    tableView.dataSource = self;
    tableView.delegate = self;
    [self.view addSubview:tableView];
    
    UIView *firstView=[[UIView alloc] initWithFrame:CGRectMake(115*kScrenWidth, 64, WIDTH-115*kScrenWidth*2, 54*kScrenHidth)];
//    firstView.backgroundColor=[UIColor yellowColor];
    UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0, 15*kScrenHidth, 20*kScrenWidth,24*kScrenHidth)];
    [img setImage:[UIImage imageNamed:@"biao@x2"]];
    [firstView addSubview:img];
    UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(img.frame.size.width+img.frame.origin.x, 0, firstView.frame.size.width-img.frame.size.width, firstView.frame.size.height)];
    [btn setTitle:@"定位到当前位置" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:14]];
   
    [firstView addSubview:btn];
    [self.view addSubview:firstView];
    UIView *line=[[UIView alloc] initWithFrame:CGRectMake(0,63+54*kScrenHidth, self.view.frame.size.width, 1)];
    line.backgroundColor=LINE_COLOE_223;
    [self.view addSubview:line];
    
    UIView *diView=[[UIView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-80*kScrenHidth, self.view.frame.size.width, 80*kScrenHidth)];
    diView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:diView];
    
    
    UIButton *nextBtn=[[UIButton alloc] initWithFrame:CGRectMake(70*kScrenWidth, 0, WIDTH-70*kScrenWidth*2, 40*kScrenHidth)];
    [nextBtn setTitle:@"添加地址" forState:UIControlStateNormal];
    [nextBtn setTitleColor:BTN_TITLE_COLOR forState:UIControlStateNormal];
    nextBtn.titleLabel.font=[UIFont systemFontOfSize:14];
    nextBtn.backgroundColor=ALL_COLOR;
    [nextBtn addTarget:self action:@selector(addAddress:) forControlEvents:UIControlEventTouchUpInside];
    nextBtn.clipsToBounds=YES;
    nextBtn.layer.cornerRadius=8;
//    UIView *diLine=[[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 1)];
//    diLine.backgroundColor=LINE_COLOE;
//    [diView addSubview:diLine];
    [diView addSubview:nextBtn];
}

- (void)addAddress:(UIButton *)btn{
    AddressViewController *addVC = [[AddressViewController alloc] init];
    [self.navigationController pushViewController:addVC animated:YES];
}
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _arr.count;
}
- (void)getJIngWei{
    if ([CLLocationManager locationServicesEnabled]) {
        //        CLog(@"--------开始定位");
        self.locationManager = [[CLLocationManager alloc]init];
        if([[UIDevice currentDevice] systemVersion].doubleValue>8.0)//如果ios是8.0以上版本
        {
            if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])//位置管理对象中有requestAlwaysAuthorization这个行为
            {
                //运行
                [self.locationManager requestAlwaysAuthorization];
            }
        }
        self.locationManager.delegate = self;
        //控制定位精度,越高耗电量越
        self.locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;
        // 总是授权
        [self.locationManager requestAlwaysAuthorization];
        self.locationManager.distanceFilter = 10.0f;
        [self.locationManager requestAlwaysAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}
//定位开启失败调用代理方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    [_locationManager startUpdatingLocation];
    CLLocation *wjq=[locations lastObject];
    CLGeocoder *geoCode=[[CLGeocoder alloc] init];
    CLLocation *newLocation = locations[0];
    NSLog(@"%f",wjq.coordinate.latitude);
    NSLog(@"%f",wjq.coordinate.longitude);
    const double x_pi = 3.14159265358979324;
    double x = wjq.coordinate.longitude, y =wjq.coordinate.latitude;
    double z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi);
    double theta = atan2(y, x) + 0.000003 * cos(x * x_pi);
    _longitude = z * cos(theta) + 0.0065;
    _latitude = z * sin(theta) + 0.006;
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
//    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
//        if (array.count > 0){
//            CLPlacemark *placemark = [array objectAtIndex:0];
//            
//            //获取城市
//            NSString *city = placemark.locality;
//            if (!city) {
//                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
//                city = placemark.administrativeArea;
//            }
//            NSLog(@"city = %@", city);//石家庄市
//            NSLog(@"--%@",placemark.name);//黄河大道221号
//            NSLog(@"++++%@",placemark.subLocality); //裕华区
//            NSLog(@"country == %@",placemark.country);//中国
//            NSLog(@"administrativeArea == %@",placemark.administrativeArea); //河北省
//        }
//        else if (error == nil && [array count] == 0)
//        {
//            NSLog(@"No results were returned.");
//        }
//        else if (error != nil)
//        {
//            NSLog(@"An error occurred = %@", error);
//        }
//    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     [[NSNotificationCenter defaultCenter] postNotificationName:@"setUpTabbar" object:self userInfo:nil];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//    static NSString *myCellIdentifer = @"myCell";
//    UITableViewCell *cell = nil;
    static NSString*iden=@"cell";
    DingWeiTableViewCell *cell=[[DingWeiTableViewCell alloc]initWithResueIdentifier:iden];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    cell.messageLabel.text=_arr[indexPath.row][@"name"];
//    cell = [tableView dequeueReusableCellWithIdentifier:myCellIdentifer];
//    
//    
//    if (!cell) {
//        cell = [[DingWeiTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:myCellIdentifer];
//    }
    
    return cell;
}


#pragma marl -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
